<template>


  <div class="yzdyh">
    <div class="config">
      <a-card title="预约配置" :bordered="false">
        <a-form :model="configForm" :rules="rules" ref="configFormRef" layout="vertical" @finish="handleSubmit">
          <a-form-item label="日期" name="date" :rules="[{ required: true, message: '请选择日期' }]">
            <a-date-picker valueFormat="YYYY-MM-DD" format="YYYY-MM-DD" v-model:value="configForm.date"
              style="width: 100%" :disabledDate="disabledDate" placeholder="请选择日期" />
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit">
                提交
              </a-button>
              <a-button @click="goto">
                查看票数
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>

      <div class="calendar">
        <div class="calendar-header">
          <span>参观日期</span>
          <span style="color:red;font-size:12px;">（每日19点开始放票）</span>
          <span style="float:right;">
            <a-icon type="left" @click="prevMonth" />
            {{ calendarYear }}年{{ calendarMonth }}月
            <a-icon type="right" @click="nextMonth" />
          </span>
        </div>
        <div class="calendar-body">
          <div class="calendar-row calendar-week">
            <span v-for="w in ['一', '二', '三', '四', '五', '六', '日']" :key="w">{{ w }}</span>
          </div>
          <div v-for="row in calendarRows" class="calendar-row">
            <span v-for="cell in row" :key="cell.date" :class="['calendar-cell', cell.statusClass]">
              <div>{{ cell.day }}</div>
              <div class="calendar-status">{{ cell.status }}</div>
            </span>
          </div>
        </div>
      </div>
    </div>

    <div id="yzdyh-todopq">
      <a-card title="抢票管理" :bordered="false">
        <template #extra>
          <a-button type="primary" @click="showAddModal">新增抢票任务</a-button>
        </template>

        <a-table :columns="columns" :data-source="ticketTasks" :loading="loading">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'requiredCount'">
              <a @click="showPersonList(record, 'required')">查看名单 ({{ record.requiredList?.length || 0 }})</a>
            </template>
            <template v-if="column.key === 'currentCount'">
              <a @click="showPersonList(record, 'current')">查看名单 ({{ record.currentList?.length || 0 }})</a>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <router-link :to="{ name: 'PersonList', params: { taskId: record.key } }">
                  <a-button type="primary">添加名单</a-button>
                </router-link>
                <a-divider type="vertical" />
                <a @click="editTask(record)">编辑</a>
                <a @click="viewSyp(record)">查看剩余票</a>
                <a-divider type="vertical" />
                <a-popconfirm title="确定要删除这个抢票任务吗？" @confirm="deleteTask(record)">
                  <a class="danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
  </div>


  <!-- 新增/编辑抢票任务对话框 -->
  <a-modal v-model:visible="taskModalVisible" :title="isEdit ? '编辑抢票任务' : '新增抢票任务'" @ok="handleTaskModalOk"
    @cancel="handleTaskModalCancel">
    <a-form :model="taskForm" :rules="taskRules" ref="taskFormRef">
      <a-form-item label="日期" name="qprq">
        <a-date-picker v-model:value="taskForm.qprq" valueFormat="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
      </a-form-item>
      <a-form-item label="抢票人员参数" name="qpcs">
        <a-textarea rows=10 v-model:value="taskForm.qpcs" />
      </a-form-item>
    </a-form>
  </a-modal>


</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import { encrypted, decrypted } from "../utils/aes.js"
import dayjs from 'dayjs'

const configFormRef = ref(null)
const isEdit = ref(false)
const taskModalVisible = ref(false)
// 加载状态
const loading = ref(false)
const configForm = reactive({
  date: null,
})

const rules = {

}
// 禁用今天之前的日期
const disabledDate = (current) => {
  return current && current < dayjs().startOf('day')
}


const handleSubmit = async (values) => {
  debugger
  // TODO: 实现查看票数逻辑
  if (!configForm.date) {
    message.warning('请先选择日期')
    return
  }
  try {
    $http.get("yzdyh/addOrder")
      .then(response => {

      })
      .catch(error => {
        console.error('请求失败:', error);
      });
  } catch (error) {
    message.error('提交失败')
  }
}

const goto = () => {
  if (!configForm.date) {
    message.warning('请先选择日期')
    return
  }
  try {
    $http.get("yzdyh/todoTg?date=" + configForm.date + "")
      .then(response => {
        calendarData.value = response.data.data.dateMap; // 假设接口返回的就是你给的对象
      })
      .catch(error => {
        console.error('请求失败:', error);
      });
  } catch (error) {
    message.error('提交失败')
  }
}

const calendarData = ref({});
const calendarMonth = ref(dayjs().month() + 1); // 当前月
const calendarYear = ref(dayjs().year());      // 当前年

const calendarRows = computed(() => {
  const daysInMonth = dayjs(`${calendarYear.value}-${calendarMonth.value}`).daysInMonth();
  const firstDay = dayjs(`${calendarYear.value}-${calendarMonth.value}-01`).day() || 7; // 1=周一
  const rows = [];
  let row = [];
  let dayCount = 1 - (firstDay - 1);
  for (let i = 0; i < 6; i++) {
    row = [];
    for (let j = 1; j <= 7; j++) {
      if (dayCount > 0 && dayCount <= daysInMonth) {
        const dateStr = `${calendarYear.value}-${String(calendarMonth.value).padStart(2, '0')}-${String(dayCount).padStart(2, '0')}`;
        const status = calendarData.value[dateStr] || '未开放';
        let statusClass = '';
        if (status.includes('有票')) statusClass = 'status-available';
        else if (status.includes('约满')) statusClass = 'status-full';
        else if (status.includes('闭馆')) statusClass = 'status-close';
        else if (status.includes('结束')) statusClass = 'status-end';
        else statusClass = 'status-default';
        row.push({ day: dayCount, date: dateStr, status, statusClass });
      } else {
        row.push({ day: '', date: '', status: '', statusClass: 'empty' });
      }
      dayCount++;
    }
    rows.push(row);
  }
  return rows;
});

const prevMonth = () => {
  if (calendarMonth.value > 1) {
    calendarMonth.value--;
  } else {
    calendarMonth.value = 12;
    calendarYear.value--;
  }
}

const columns = [
  {
    title: '日期',
    dataIndex: 'qprq',
    key: 'qprq',
  },
  {
    title: '抢票人员参数',
    dataIndex: 'qpcs',
    key: 'qpcs',
  },
  {
    title: '抢票结果',
    dataIndex: 'qpjg',
    key: 'qpjg',
  }, {
    title: '是否已抢票',
    dataIndex: 'sfyq',
    key: 'sfyq',
  }
]
// 处理抢票任务模态框取消
const handleTaskModalCancel = () => {
  taskModalVisible.value = false
}


// 处理抢票任务模态框确认
const handleTaskModalOk = () => {
  taskFormRef.value.validate().then(() => {
    const taskData = {
      ...taskForm
    }
    debugger
    $http.post("task/addTask", taskData)
      .then(response => {
        taskModalVisible.value = false
        message.success('保存成功')
      })
      .catch(error => {
        console.error('请求失败:', error);
      });
  })
}

// 抢票任务数据
const ticketTasks = ref([
  {
    key: '1',
    qprq: '2024-03-20',
    qpcs: '张三,李四',
    qpjg: '抢票成功',
    sfyq: '是',
  },
  {
    key: '2',
    qprq: '2024-03-21',
    qpcs: '张三,李四',
    qpjg: '抢票失败',
    sfyq: '否',
  },
])


// 表单引用
const taskFormRef = ref(null)

// 表单数据
const taskForm = reactive({})


const showAddModal = () => {
  debugger
  isEdit.value = false
  taskForm.id = ""
  taskForm.qprq = null
  taskForm.qpcs = null
  taskModalVisible.value = true
}



const nextMonth = () => {
  if (calendarMonth.value < 12) {
    calendarMonth.value++;
  } else {
    calendarMonth.value = 1;
    calendarYear.value++;
  }
}




















</script>

<style scoped>
.yzdyh {
  display: grid;
  grid-template-columns: 400px auto;
}

.yzdyh-todopq {}

.config {
  min-width: 400px;
}

:deep(.ant-form-item-label) {
  font-weight: 500;
}

.calendar {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-top: 24px;
}

.calendar-header {
  font-weight: bold;
  margin-bottom: 8px;
}

.calendar-row {
  display: flex;
}

.calendar-week span {
  flex: 1;
  text-align: center;
  font-weight: bold;
}

.calendar-cell {
  flex: 1;
  text-align: center;
  padding: 4px 0;
  min-height: 40px;
}

.status-available {
  color: #52c41a;
}

.status-full {
  color: #faad14;
}

.status-close {
  color: #bfbfbf;
}

.status-end {
  color: #ff4d4f;
}

.status-default {
  color: #d9d9d9;
}

.empty {
  background: none;
}

.calendar-status {
  font-size: 12px;
}
</style>